package com.lg.controller;

import com.lg.feign.ConsumerFeignService;
import com.lg.service.ConsumerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/consumer")
public class NacosController {

	@Value("${spring.application.name}")
	private String appName;
	
	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private ConsumerFeignService consumerFeignService;
	
	@Autowired
	private ConsumerService consumerService;

	@GetMapping("/index")
	public String index() {
		String str = consumerService.echo("this is ConsumerService");
		return str;
	}

	@GetMapping("/app-name")
	public String echoAppName() {
		// 使用 LoadBalanceClient 和 RestTemolate 结合的方式来访问
		ServiceInstance serviceInstance = loadBalancerClient.choose("torn-provider");
		String url = String.format("http://%s:%s/index/echo/%s", serviceInstance.getHost(), serviceInstance.getPort(), appName);
		System.out.println("request url:" + url);
		return restTemplate.getForObject(url, String.class);
	}
	
	@GetMapping("/app-nameFeign/{id}")
	public String echoAppNameFeign(@PathVariable String id) {
		// 使用 feign调用
		String echo = consumerFeignService.echo(appName);
		return echo + "--id=" + id;
	}

}